﻿﻿using DeviceCommons.Validation;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Models.V1
{
    public class DeviceMessageChild : IDeviceMessageChild
    {
        private readonly Dictionary<string, IDeviceMessageInfo> _children = [];
        private readonly List<string> _insertionOrder = []; // 维护插入顺序

        public DeviceMessageChild()
        {
        }

        public byte Count => (byte)_children.Count;

        public IDeviceMessageInfo[]? ChildArray
        {
            get => [.. _insertionOrder.Select(did => _children[did])]; // 按插入顺序返回
            set
            {
                _children.Clear();
                _insertionOrder.Clear();
                if (value != null)
                {
                    foreach (var dev in value)
                    {
                        if (dev != null)
                        {
                            if (!string.IsNullOrEmpty(dev.DID))
                            {
                                var did = dev?.DID ?? "";
                                if (!_children.ContainsKey(did)) // 确保DID不重复
                                {
                                    _children[did] = dev ?? new DeviceMessageInfo();
                                    _insertionOrder.Add(did);
                                }
                            }
                        }
                        else throw new ArgumentNullException("初始化后再赋值");
                    }
                }
            }
        }

        public int DataLength => 1 + (ChildArray?.Sum(i => i.DataLength) ?? 0);

        public void AddOrUpdateChild(IDeviceMessageInfo child)
        {
            if (string.IsNullOrEmpty(child.DID))
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InvalidDeviceId,
                    "子设备的DID不能为空字符串",
                    nameof(child.DID),
                    "非空字符串",
                    child.DID ?? "null");

            var did = child?.DID ?? "";
            
            // 如果是新的DID，添加到插入顺序列表中
            if (!_children.ContainsKey(did))
            {
                _insertionOrder.Add(did);
            }
            
            _children[did] = child ?? new DeviceMessageInfo();
        }
    }
}
